import csv
from typing import List, Tuple
from .medical_record import MedicalRecord


class AuditResult:
    """
    审核结果类
    """
    
    def __init__(self, patient_id: str, is_valid: bool, errors: List[str]):
        self.patient_id = patient_id
        self.is_valid = is_valid
        self.errors = errors
    
    def get_status(self) -> str:
        """获取审核状态"""
        return "通过" if self.is_valid else "不通过"
    
    def get_details(self) -> str:
        """获取详细信息"""
        if self.is_valid:
            return "审核通过"
        return "; ".join(self.errors)


class ResultOutput:
    """
    结果输出模块
    将审核结果保存到CSV文件并统计审核情况
    """
    
    def __init__(self, output_file: str):
        self.output_file = output_file
        self.total_count = 0
        self.pass_count = 0
    
    def write_results(self, audit_results: List[AuditResult]) -> None:
        """
        将审核结果写入CSV文件
        
        Args:
            audit_results (List[AuditResult]): 审核结果列表
        """
        # 更新统计信息
        self.total_count += len(audit_results)
        self.pass_count += sum(1 for result in audit_results if result.is_valid)
        
        # 写入CSV文件
        with open(self.output_file, 'a', newline='', encoding='utf-8') as csvfile:
            writer = csv.writer(csvfile)
            
            # 如果是第一次写入，添加表头
            if self.total_count == len(audit_results):
                writer.writerow(['患者ID', '审核结果', '详情'])
            
            # 写入审核结果
            for result in audit_results:
                writer.writerow([
                    result.patient_id,
                    result.get_status(),
                    result.get_details()
                ])
    
    def get_statistics(self) -> Tuple[int, int, float]:
        """
        获取审核统计信息
        
        Returns:
            Tuple[int, int, float]: (总审核量, 通过量, 通过率)
        """
        if self.total_count == 0:
            return 0, 0, 0.0
        
        pass_rate = (self.pass_count / self.total_count) * 100
        return self.total_count, self.pass_count, pass_rate
    
    def print_statistics(self) -> None:
        """打印审核统计信息"""
        total, passed, rate = self.get_statistics()
        print(f"总审核量: {total}")
        print(f"通过量: {passed}")
        print(f"通过率: {rate:.2f}%")